import { WxRequest } from './request'
import { toast } from './extendApi'
import { userStore } from '@/store/userstore'
const errorMap= {
  '400': '访问数据错误',
  '500': '服务器内部错误',
  '501': '登录失败',
  '502': '登录凭证过期',
  '503': '服务器正忙，请稍后再试',
  '504': '非法请求',
  '505': '请求出错',
  '506': '未经授权',
  '507': '禁止访问',
  '508': '请求的资源找不到',
  '509': '中间件调用失败',
  '510': '请求过于频繁'
}
//实例化请求
const instance = new WxRequest({
  baseUrl: getApp().globalData.baseUrl,
  timeout: 60000
})

//请求拦截器
instance.interceptors.request = (config: any) => {
  //可以加token 等
  let token  = userStore.getToken()
  if (!token || token == undefined || token == null  || token == '') {
    const whiteUrl = getApp().globalData.whiteUrl as string[]
    const whiteCount = whiteUrl.filter(item => config.url.search(item) >= 0).length
    if (whiteCount == 0) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    }
  } else {
    // 如果有token就请求头默认带上
    config.header['WXToken'] = token;
  }

  return config
}


//响应拦截器
instance.interceptors.response = (response: any) => {
  //判断请求是否成功
  // 把接口请求的值返回过去 这个方法放回值就是放回值
  //如果是错误  return  Promise.reject(response)
   if (response.data.code === 200) {
    return response.data
  }
  return errorDetail(response)
}


const errorDetail = (response: any) => {
 
  const errMsg =errorMap[response.data.code+'']
  toast({
        title: response.data.msg || errMsg,
        icon: 'error',
        duration: 2000
  })
  return Promise.reject(response)
}

export default instance